package org.geektimes.projects.user.web.listener;

import org.geektimes.projects.user.domain.User;
import org.geektimes.projects.user.management.UserManager;
import org.geektimes.projects.user.management.book.Book;
import org.geektimes.projects.user.management.book.BookManagement;

import javax.management.InstanceAlreadyExistsException;
import javax.management.MBeanRegistrationException;
import javax.management.MBeanServer;
import javax.management.MalformedObjectNameException;
import javax.management.NotCompliantMBeanException;
import javax.management.ObjectName;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import java.lang.management.ManagementFactory;
import java.util.logging.Logger;

public class JMXTestListener implements ServletContextListener {

    private Logger logger = Logger.getLogger(this.getClass().getName());

    @Override
    public void contextInitialized(ServletContextEvent sce) {

        // week03 homework item 1 (necessary)
        try {
            testJolokia();
        } catch (MalformedObjectNameException | NotCompliantMBeanException
                | InstanceAlreadyExistsException | MBeanRegistrationException | InterruptedException e) {
            e.printStackTrace();
        }

    }

    @Override
    public void contextDestroyed(ServletContextEvent sce) {

    }

    private void testJolokia() throws MalformedObjectNameException, NotCompliantMBeanException, InstanceAlreadyExistsException, MBeanRegistrationException, InterruptedException {
        MBeanServer mBeanServer = ManagementFactory.getPlatformMBeanServer();
        // jolikia 是 namespace
        ObjectName bookObjName = new ObjectName("jolokia:type=Book");
        Book book = new Book();
        mBeanServer.registerMBean(new BookManagement(book), bookObjName);

        ObjectName userObjName = new ObjectName("jolokia:type=User");
        User user = new User();
        mBeanServer.registerMBean(new UserManager(user), userObjName);

//        while (true) {
//            Thread.sleep(5000);
//            logger.info(book.toString());
//            logger.info(user.toString());
//        }
    }
}
